package com.xiaoming.mojcodesandbox;

import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.ArrayUtil;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.*;
import com.github.dockerjava.api.model.*;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.command.ExecStartResultCallback;
import com.xiaoming.mojcodesandbox.model.ExecuteCodeRequest;
import com.xiaoming.mojcodesandbox.model.ExecuteCodeResponse;
import com.xiaoming.mojcodesandbox.model.ExecuteMessage;
import com.xiaoming.mojcodesandbox.model.JudgeInfo;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.sql.Time;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Component
public class JavaDockerCodeSandbox extends JavaCodeSandBoxTemplate {



    private static boolean FIRST_INIT=true;
    private static final long TIME_OUT=1L;

    @Override
    public List<ExecuteMessage> runFile(File userCodeFile, List<String> inputList) {
        //3.创建容器 把编译后文件上传到容器
        String userCodeParentPath=userCodeFile.getParentFile().getAbsolutePath();
        //创建默认docker Client
        DockerClient dockerClient= DockerClientBuilder.getInstance("unix:///var/run/docker.sock").build();
        //拉取镜像
        String image="openjdk:8-alpine";
        if(FIRST_INIT)
        {
            PullImageCmd pullImageCmd=dockerClient.pullImageCmd(image);
            PullImageResultCallback pullImageResultCallback=new PullImageResultCallback(){
                @Override
                public void onNext(PullResponseItem item) {
                    System.out.println("下载镜像");
                    super.onNext(item);
                }
            };
            try {
                pullImageCmd.exec(pullImageResultCallback)
                        .awaitCompletion();
            } catch (InterruptedException e) {
                System.out.println("拉取镜像异常");
                throw new RuntimeException(e);
            }

        }
        FIRST_INIT=false;

        //创建容器
        CreateContainerCmd containerCmd = dockerClient.createContainerCmd(image);
        HostConfig hostConfig=new HostConfig();
        //挂载文件
        hostConfig.setBinds(new Bind(userCodeParentPath,new Volume("/app")));
        //内存限制 100M
        hostConfig.withMemory(100*1000*1000L);
        //限制cpu
        hostConfig.withCpuCount(1L);

        CreateContainerResponse createContainerResponse = containerCmd
                //禁用网络
                .withNetworkDisabled(true)
                //禁止向root目录写文件
                .withReadonlyRootfs(true)
                .withAttachStderr(true)
                .withAttachStdin(true)
                .withAttachStdout(true)
                .withTty(true)
                .withHostConfig(hostConfig)
                .exec();
        System.out.println(createContainerResponse);
        System.out.println("创建容器成功");
        String containId=createContainerResponse.getId();

        //启动容器
        StartContainerCmd startContainerCmd = dockerClient.startContainerCmd(containId);
        startContainerCmd.exec();

        //执行命令并获取结果
        List<ExecuteMessage> executeMessageList=new ArrayList<>();
        for (String inputStr : inputList) {
            StopWatch stopWatch=new StopWatch();
            String[] inputArray= inputStr.split(" ");
            String[] cmdArray=ArrayUtil.append(new String[]{"java","-cp","/app","Main"},inputArray);

            //创建命令
            ExecCreateCmdResponse execCreateCmdResponse = dockerClient.execCreateCmd(containId)
                    .withCmd(cmdArray)
                    .withAttachStderr(true)
                    .withAttachStdout(true)
                    .withAttachStdin(true)
                    .exec();
            System.out.println("创建执行命令:"+execCreateCmdResponse);
            String id = execCreateCmdResponse.getId();
            //收集运行结果信息
            ExecuteMessage executeMessage=new ExecuteMessage();
            final String[] errMessage = {null};
            final String[] message = {null};
            long time=0;
            final boolean[] timeout = {true};
            ExecStartResultCallback execStartResultCallback = new ExecStartResultCallback() {
                @Override
                public void onComplete() {
                    //执行完成 则没有超时
                    timeout[0] =false;
                    super.onComplete();
                }

                @Override
                public void onNext(Frame frame) {
                    StreamType streamType = frame.getStreamType();
                    if (StreamType.STDERR.equals(streamType)) {
                        errMessage[0] = new String(frame.getPayload());
                        System.out.println("错误：" + errMessage[0]);
                    } else {
                        message[0] = new String(frame.getPayload());
                        System.out.println("正确：" + message[0]);
                    }
                    super.onNext(frame);
                }


        };
            final long[] maxMemory={0L};
            //获取内存占用
            StatsCmd statsCmd = dockerClient.statsCmd(containId);
            ResultCallback<Statistics> statisticsResultCallback = statsCmd.exec(new ResultCallback<Statistics>() {
                @Override
                public void onNext(Statistics statistics) {
                    maxMemory[0] = Math.max(statistics.getMemoryStats().getUsage(), maxMemory[0]);
                    //System.out.println("内存占用：" + statistics.getMemoryStats().getUsage());

                }

                @Override
                public void onStart(Closeable closeable) {

                }


                @Override
                public void onError(Throwable throwable) {

                }

                @Override
                public void onComplete() {

                }

                @Override
                public void close() throws IOException {

                }
            });
            statsCmd.exec(statisticsResultCallback);

            try {
                //执行命令
                stopWatch.start();
                dockerClient.execStartCmd(id)
                        .exec(execStartResultCallback)
                        .awaitCompletion(TIME_OUT,TimeUnit.MINUTES);
                //Thread.sleep(10000L);
                stopWatch.stop();
                //执行时间
                time=stopWatch.getLastTaskTimeMillis();
                statsCmd.close();
            } catch (InterruptedException e) {
                System.out.println("程序执行异常");
                throw new RuntimeException(e);
            }

            String messageStr=null;
            if(message[0]!=null)
            {
                messageStr=message[0].substring(message[0].indexOf('：')+1,message[0].indexOf("\n"));
            }
            String errMessageStr=null;
            if( errMessage[0]!=null) {
                errMessageStr = errMessage[0].substring(errMessage[0].indexOf('：') + 1, errMessage[0].indexOf("\n"));
            }

            executeMessage.setMessage(messageStr);
            executeMessage.setErrorMessage(errMessageStr);
            executeMessage.setTime(time);
            executeMessage.setMemory(maxMemory[0]);
            executeMessageList.add(executeMessage);
            errExecuteCodeResponse=new ExecuteCodeResponse();
            if(timeout[0]==true)
            {
                JudgeInfo judgeInfo=new JudgeInfo();
                judgeInfo.setMessage("超时");
                judgeInfo.setTime(time);
                errExecuteCodeResponse.setJudgeInfo(judgeInfo);
            }
        }
        return executeMessageList;
    }


}
